package com.samoilovich.belarustoday.rates;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.samoilovich.belarustoday.Constants;
import com.samoilovich.belarustoday.R;
import com.samoilovich.belarustoday.adapters.RatesAdapter;
import com.samoilovich.belarustoday.basefragments.BaseFragmentActivity;
import com.samoilovich.belarustoday.datemodel.Rates;
import com.samoilovich.belarustoday.handlers.RatesHandler;
import com.samoilovich.belarustoday.tools.Utility;

public class RatesActivity extends BaseFragmentActivity implements TabHost.OnTabChangeListener {
    private final int TEXT_SIZE = 17;
    private View mViewNoConnection;
    private RatesAdapter mAdapter;
    private Rates mRates;
    private TabHost mTabHost;
    private TextView mTitle;
    private InternetBroadcastReceiver mReceiver;
    private IntentFilter mFilter;
    private boolean mWasLostInternetConnection;
    private ProgressBar mProgressBar;
    private ListView mRatesListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUpdateButtonState = true;
        setContentView(R.layout.rates);
        Utility.clearBackStack(this);
        Utility.initImageLoader(this);
        prepareViews();
        prepareActionBarViews();
        prepareRatesListView();
        prepareTabWidget();
        getCategories(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        registerInternetBroadcastReceiver();
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
        mWasLostInternetConnection = false;
    }

    @Override
    public void onTabChanged(String s) {
        updateScreen();
    }

    @Override
    public void updateAllData() {
        updateCategories(this);
    }

    public void update(final Rates rates) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mRates = rates;
                mTitle.setText(mRates.getTime());
                mProgressBar.setVisibility(View.GONE);
                mTabHost.setVisibility(View.VISIBLE);
                updateScreen();
            }
        });
    }

    // -----------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------
    private void prepareViews() {
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar_ratesWait);
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mRatesListView = (ListView) findViewById(R.id.listView_rates);
    }


    private void prepareActionBarViews() {
        mRates = new Rates();
        ((TextView) findViewById(R.id.textView_backLabel)).setText(R.string.main_label);
        mTitle = (TextView) findViewById(R.id.textView_title);
        mTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, TEXT_SIZE);
        RelativeLayout backView = (RelativeLayout) findViewById(R.id.relativeLayout_back);

        findViewById(R.id.button_option).setVisibility(View.INVISIBLE);
        backView.setVisibility(View.VISIBLE);
        backView.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                onBackPressed();
            }
        });

        (findViewById(R.id.view_action)).setVisibility(View.GONE);

        Button optionsButton = (Button) findViewById(R.id.button_option);
        (findViewById(R.id.view_action)).setVisibility(View.VISIBLE);
        optionsButton.setVisibility(View.VISIBLE);
        optionsButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                setOptionsFragment(getString(R.string.back_label));
            }
        });
    }

    private void prepareTabWidget() {
        TabSpec tab;

        mTabHost.setup();
//        mTabHost.removeAllViews();
        tab = mTabHost.newTabSpec(Constants.DOLLAR_TAG);
        tab.setIndicator(Utility.getRatesTabView(this, R.string.dollar_label, View.VISIBLE));
        tab.setContent(R.id.listView_rates);
        mTabHost.addTab(tab);

        tab = mTabHost.newTabSpec(Constants.EURO_TAG);
        tab.setIndicator(Utility.getRatesTabView(this, R.string.euro_label, View.VISIBLE));
        tab.setContent(R.id.listView_rates);
        mTabHost.addTab(tab);

        tab = mTabHost.newTabSpec(Constants.RUBLE_TAG);
        tab.setIndicator(Utility.getRatesTabView(this, R.string.ruble_label, View.VISIBLE));
        tab.setContent(R.id.listView_rates);
        mTabHost.addTab(tab);

        tab = mTabHost.newTabSpec(Constants.EUR_USD_TAG);
        tab.setIndicator(Utility.getRatesTabView(this, R.string.eur_usd_label, View.VISIBLE));
        tab.setContent(R.id.listView_rates);
        mTabHost.addTab(tab);

        tab = mTabHost.newTabSpec(Constants.USD_RUB_TAG);
        tab.setIndicator(Utility.getRatesTabView(this, R.string.usd_rub_label, View.INVISIBLE));
        tab.setContent(R.id.listView_rates);
        mTabHost.addTab(tab);

        mTabHost.setOnTabChangedListener(this);

        /* if set current tab only by mTabHost.setCurrentTab(0), it isn't work :( */
        mTabHost.setCurrentTab(1);
        mTabHost.setCurrentTab(0);
    }

    private void prepareRatesListView() {
        if (mRatesListView == null) {
            prepareViews();
        }
        mViewNoConnection = findViewById(R.id.view_noConnection);
        mAdapter = new RatesAdapter(this, mRates.getDollars(), R.layout.rates_list_item);
        mRatesListView.setAdapter(mAdapter);
    }

    private void updateScreen() {
        int index = mTabHost.getCurrentTab();
        mAdapter.setRates(mRates.getCurrency(index));
    }


    private void registerInternetBroadcastReceiver() {
        if (mReceiver == null) {
            mReceiver = new InternetBroadcastReceiver();
        }
        if (mFilter == null) {
            mFilter = new IntentFilter();
            mFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            mFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        }
        registerReceiver(mReceiver, mFilter);
    }

    private void onReceiveInternetIntent(boolean hasInternetConnection) {
        if (mAdapter == null) {
            prepareRatesListView();
        }
        if (hasInternetConnection) {
                if (mWasLostInternetConnection && mRates == null) {
                   getCategories(this);
                }
            mViewNoConnection.setVisibility(View.GONE);
        } else {
            mWasLostInternetConnection = true;
            if (mRates == null) {
                mViewNoConnection.setVisibility(View.VISIBLE);
            }
        }
    }

    private void updateCategories(Context context) {
        if (mRatesListView == null || mProgressBar == null || mTabHost == null) {
            prepareViews();
        }
//        mRatesListView.scrollTo(0, 0);
        mProgressBar.setVisibility(View.VISIBLE);
        mTabHost.setVisibility(View.GONE);
        getCategories(context);
    }

    private void getCategories(Context context) {
        mRates = null;
        if (Utility.hasInternetConnection(context)) {
            RatesHandler.getInstance().getRates(this);
        }
    }

    // -----------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------
    private class InternetBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            boolean state = Utility.hasInternetConnection(RatesActivity.this);
            onReceiveInternetIntent(state);
            mUpdateButtonState = state;
        }
    }


}